package com.sync.hkmjsyncdata.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sync.hkmjsyncdata.config.isecurecenter.IsecureCenterUtilsService;
import com.sync.hkmjsyncdata.pojo.po.HkPoint;
import com.sync.hkmjsyncdata.service.IHkPointService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SyncMjPoint {


    static final String PAGE_NO_KEY = "pageNo";
    static final String PAGE_SIZE_KEY = "pageSize";

    @Resource
    IsecureCenterUtilsService centerUtilsService;


    @Resource
    IHkPointService pointService;


   // {"code":"0","msg":"success","data":{"total":3,"pageNo":1,"pageSize":100,"list":[{"indexCode":"b845b84b77864a6ca18478d1cab91663","name":"二次舱门口_门_1","resourceType":"door","doorNo":"1","doorSerial":1,"description":"","parentIndexCode":"8b9d3f9b52fc4024a02a2c7f0915db7c","regionIndexCode":"root000000","treatyType":"isup5_reg","channelType":"door","channelNo":"1","controlOneId":"8b9d3f9b52fc4024a02a2c7f0915db7c","controlTwoId":"","readerInId":"ea5374eb90b7450fa4ebe55aad403d07","readerOutId":"","isCascade":0,"createTime":"2025-06-25T21:03:02.271+08:00","updateTime":"2025-06-25T21:04:29.647+08:00","sort":1845,"disOrder":1845,"regionName":"根节点","regionPath":"@root000000@","regionPathName":"根节点"},{"indexCode":"dc80afdcd36444f3aef592aaec66403f","name":"储能区门口_门_1","resourceType":"door","doorNo":"1","doorSerial":1,"description":"","parentIndexCode":"d6c7cf0ebbcc4350add5e731cb7cc83f","regionIndexCode":"root000000","treatyType":"isup5_reg","channelType":"door","channelNo":"1","controlOneId":"d6c7cf0ebbcc4350add5e731cb7cc83f","controlTwoId":"","readerInId":"8013efb1a083491fa380b8273f945400","readerOutId":"","isCascade":0,"createTime":"2025-06-25T20:59:35.804+08:00","updateTime":"2025-06-25T21:03:39.304+08:00","sort":1842,"disOrder":1842,"regionName":"根节点","regionPath":"@root000000@","regionPathName":"根节点"},{"indexCode":"0a47727b5eaf43928f17737cfe243973","name":"运行管理中心大门口","resourceType":"door","doorNo":"1","doorSerial":1,"description":"","parentIndexCode":"bb147c3574e24ff9b085e6469f9725cd","regionIndexCode":"root000000","treatyType":"hiksdk_net","channelType":"door","channelNo":"1","controlOneId":"bb147c3574e24ff9b085e6469f9725cd","controlTwoId":"","readerInId":"3e896d08ae8948718c95387c93d8c374","readerOutId":"","isCascade":0,"createTime":"2025-05-14T17:32:36.425+08:00","updateTime":"2025-05-29T12:15:40.304+08:00","sort":1,"disOrder":1,"regionName":"根节点","regionPath":"@root000000@","regionPathName":"根节点"}]}}





    /**
     * 同步海康区域
     */
    @XxlJob("SyncMjPoint")
    public void SyncMjPointData(){
        XxlJobHelper.log("开始同步海康门禁点位信息");
        LambdaQueryWrapper<HkPoint> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(HkPoint::getOpTyp,4).last(" limit 1");
        List<HkPoint> allResult=pointService.list();
        if(ObjectUtils.isNotEmpty(allResult)){
            XxlJobHelper.log("数据库已有海康门禁点信息：{}条", allResult.size());
//            List<HkPoint> result=pointService.list(queryWrapper);
//            if(ObjectUtils.isEmpty(result)){
//                XxlJobHelper.log("数据库已有海康门禁点信息未推送工业互联网,停止拉取");
//                return;
//            }
        }
        List<HkPoint> newPoints=new ArrayList<>();
        SyncMjPointDataByHk(1,newPoints);
        bulidMjPointInfo(allResult,newPoints);
    }

    private void SyncMjPointDataByHk(int pageNo, List<HkPoint> newPoints) {
        JSONObject pointParams = new JSONObject();
        pointParams.put(PAGE_NO_KEY, pageNo);
        pointParams.put(PAGE_SIZE_KEY, 1000);
        XxlJobHelper.log("同步海康门禁点位信息查询条件：{}", pointParams.toJSONString());
        String resultInfo = centerUtilsService.doPost("/api/resource/v2/door/search", pointParams.toJSONString());
        XxlJobHelper.log("同步海康门禁点位信息返回：{}", resultInfo);
        if (StringUtils.isNotBlank(resultInfo)) {
            JSONObject pointResult= JSON.parseObject(resultInfo);
            JSONObject pointData = pointResult.getJSONObject("data");
            if (ObjectUtils.isNotEmpty(pointData) && ObjectUtils.isNotEmpty(pointData.getJSONArray("list"))) {
                JSONArray list = pointData.getJSONArray("list");
                for (int i = 0; i < list.size(); i++) {
                    JSONObject pointInfo = list.getJSONObject(i);
                    newPoints.add(new HkPoint()
                            .setMjdId(pointInfo.getString("indexCode"))
                            .setMjdName(pointInfo.getString("name"))
                            .setMjdNot(pointInfo.getString("description"))
                            .setAreaId(pointInfo.getString("regionIndexCode"))
                            .setMjState("A")
                            .setMjTyp(0)
                            .setMjGroup("生产组")
                            .setCyTyp("CYFD")
                            .setFpTyp("Y")
                            .setMjFlg(1)
                            .setScqyTyp("Y")
                            .setOpTyp(1));
                }
                if(ObjectUtils.isNotEmpty(list)){
                    SyncMjPointDataByHk(pageNo+1,newPoints);
                }
            } else {
                XxlJobHelper.log("同步海康门禁点位信息失败");
            }
        }



    }


    private void bulidMjPointInfo(List<HkPoint> allResult,List<HkPoint> hkPointList) {
        Map<String, HkPoint> oldPointMap = allResult.stream().collect(Collectors.toMap(HkPoint::getMjdId, point -> point, (a, b) -> b));
        if(ObjectUtils.isEmpty(oldPointMap)){
            pointService.saveBatch(hkPointList);
        }else {
            List<HkPoint> addHkPointList=new ArrayList<>();
            List<HkPoint> updatePointList=new ArrayList<>();
            List<String> ids=new ArrayList<>();
            hkPointList.forEach(point->{
                ids.add(point.getMjdId());
                HkPoint oldPoint= oldPointMap.get(point.getMjdId());
                if(ObjectUtils.isEmpty(oldPoint)){
                    addHkPointList.add(point);
                }else {
                    updatePointList.add(point.setOpTyp(oldPoint.getOpTyp()==4?2:oldPoint.getOpTyp()));
                }
            });
            List<HkPoint> deletePointList=allResult.stream().filter(point->(!ids.contains(point.getMjdId()))&&point.getOpTyp()==4).toList();
            deletePointList.forEach(nreg->nreg.setOpTyp(3));
            XxlJobHelper.log("新增海康门禁点信息：{}条",addHkPointList.size());
            pointService.saveBatch(addHkPointList);
            XxlJobHelper.log("修改海康门禁点信息：{}条",updatePointList.size());
            pointService.updateBatchById(updatePointList);
            XxlJobHelper.log("删除海康门禁点信息：{}条",updatePointList.size());
            pointService.updateBatchById(deletePointList);
        }


    }

}
